package com.ym.wcp.framework.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;

import java.io.IOException;

public class XmlUtil {

    private final static XmlMapper xm;

    static {
        xm = new XmlMapper();
        xm.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        xm.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
        xm.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        xm.enable(MapperFeature.USE_STD_BEAN_NAMING);
        xm.setPropertyNamingStrategy(PropertyNamingStrategy.UPPER_CAMEL_CASE);
    }

    public static <T> T toBen(String xml, Class<T> cls) {
        try {
            return xm.readValue(xml, cls);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String toXml(Object obj) {
        try {
            xm.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return "";
    }
}
